#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "config/config.h"


int
in_file(char *login,char *filename)
{
  FILE* file = fopen(filename,"r");
  char buff[256]; // juste par securite, on suppose que la ligne pourrait etre tres grande
  while (fgets(buff,BUFFER_SIZE,file) != NULL)
    {
      if (strcmp(login,buff) == 0)
	{
	  fclose(file);
	  return 1;
	}
    }

  fclose(file);
  return 0;
}


int 
authorization(char *code_login)
{
  if (code_login == NULL || strlen(code_login) == 0)
    return 0;

  if (strlen(code_login) > 42)
    return 0;//code trop gros ?

  char type[32];
  char code[64];

  
  if (sscanf(code_login,"%s %s",type,code) != 2)
    return 0; //problem

  if (strcmp(type,"Basic")!=0 || strlen(code)==0)
    return 0;

  int tube1[2];
  int tube2[2];
  pipe(tube1);
  pipe(tube2);

  if (fork() == 0)
    {
      close(tube1[0]);
      int r = write(tube1[1],code,strlen(code)*sizeof(char));
      if (r <= 0)
	{
	  perror("write");
	  exit(1);
	}
      exit(0);
    }


  if (fork()==0)
    {
      dup2(tube1[0],0);
      close(tube1[0]);
      close(tube1[1]);
      dup2(tube2[1],1);
      close(tube2[1]);
      execlp("base64","base64","-d",NULL);
      perror("probleme base64\n");
      exit(1);
    }
  
  char buffer[BUFFER_SIZE];
  char *login = malloc(sizeof(char)*BUFFER_SIZE);
  int taille = BUFFER_SIZE;

  
  close(tube1[0]);
  close(tube1[1]);
  close(tube2[1]);

  int r;
  int off = 0;
  
  while ((r = read(tube2[0],buffer, BUFFER_SIZE -1)) > 0)
    {
      buffer[r] = '\0';
      
      if (sizeof(char)*(strlen(login) + r + 1) > taille)
	{
	  taille <<= 1;
	  login = realloc(login, sizeof(char)*taille);
	}
      
      strcpy(login + off,buffer);
      
      off += r;
    }

  close(tube2[0]);
    
  login = realloc(login,sizeof(char)*(strlen(login)+1));

  for(int i = 0 ; i < 2 ; i++) {//on tue les zombis
    wait(NULL); 
  }
  


  int infile = in_file(login,PSWDFILE);

  free(login);

  return infile;
}



/*
int 
main()
{
  printf("%d\n",authorization(NULL));
  return 0;

  }*/

